package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;

@Service("customerService")
@Transactional
public class CustomerServiceImpl implements CustomerService {
	@Autowired
	private CustomerRepository customerRepository;

	@Override
	public List<Customer> findCustomerListNoFixedAreaId() {
		// TODO Auto-generated method stub
		List<Customer> list = customerRepository.findByFixedAreaIdIsNull();
		// System.out.println(list);
		return list;
	}

	@Override
	public List<Customer> findCustomerListByFixedAreaId(String fixedAreaId) {
		// TODO Auto-generated method stub
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	@Override
	public void updateFixedAreaIdByCustomerIds(String fixedAreaId, String customerIds) {
		// TODO Auto-generated method stub
		// 1先去掉原来的所有关联
		// 查询所有关联某定区的客户列表
		List<Customer> customerOldList = customerRepository.findByFixedAreaId(fixedAreaId);
		for (Customer customer : customerOldList) {
			// 将定区编号置为空
			customer.setFixedAreaId(null);
			// 快照更新
			// 等flush
		}
		// 2再关联新的关联
		if (StringUtils.isNotBlank(customerIds) && !customerIds.equals("null")) {
			// 2再关联新的关联
			String[] ids = customerIds.split(",");
			for (String id : ids) {
				// 先查询
				Customer customer = customerRepository.findOne(Integer.parseInt(id));
				// 快照更新
				customer.setFixedAreaId(fixedAreaId);
				// 等flush

			}
		}
	}

	@Override
	public void saveCustomer(Customer customer) {
		// TODO Auto-generated method stub
		customerRepository.save(customer);
	}

	@Override
	public void updateTypeByMobilePhone(String mobilePhone, Integer type) {
		// TODO Auto-generated method stub
		customerRepository.updateTypeByMobilePhone(mobilePhone, type);

	}

	@Override
	public Customer findFixedAreaIdByAddress(String address) {
		// TODO Auto-generated method stub
		// 获得根据客户查询定区的编号集合
		// System.out.println(address);
		List<Customer> customerList = customerRepository.findByAddress(address);
		// 判断结果是否为空 (判断一个String类型的数据是否为空最好判断是否为空
		// 在isEmpty,否则只判断isEmpty不判断是否为null,如果为null,容易报空指针)
		if (customerList != null && !customerList.isEmpty()) {
			Customer customer = customerList.get(0);
			// 封装到bean
			Customer c = new Customer();
			c.setFixedAreaId(customer.getFixedAreaId());
			return c;
		} else {
			return null;
		}
	}

}
